package com.huashi.dealer.core.util;

import com.huashi.dealer.commonEntity.UploadFile;
import com.huashi.dealer.core.exception.CommonException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * 文件上传工具类
 */
@Component
@Slf4j
public class FileUploadUtil {

    @Value("${upload.path:uploads}")
    private String uploadPath;

    @Value("${upload.domain:}")
    private String uploadDomain;

    /**
     * 上传图片文件
     * @param file 文件
     * @return 文件信息
     */
    public UploadFile uploadImage(MultipartFile file) {
        try {
            // 验证文件
            if (file == null || file.isEmpty()) {
                throw new CommonException("上传文件不能为空");
            }

            // 获取文件信息
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null) {
                throw new CommonException("文件名不能为空");
            }

            // 生成唯一文件名
            String fileExt = getFileExtension(originalFilename);
            String fileName = generateFileName(fileExt);
            
            // 创建上传目录
            String datePath = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
            String relativePath = datePath + "/" + fileName;
            Path uploadDir = Paths.get(uploadPath, datePath);
            if (!Files.exists(uploadDir)) {
                Files.createDirectories(uploadDir);
            }

            // 保存文件
            Path filePath = uploadDir.resolve(fileName);
            file.transferTo(filePath.toFile());

            // 构建文件URL
            // 统一使用/uploads作为访问路径
            String fileUrl = uploadDomain + "/" + relativePath;

            // 返回文件信息
            UploadFile fileInfo = new UploadFile();
            fileInfo.setFileName(fileName);
            fileInfo.setFileUrl(fileUrl);
            fileInfo.setExtension(fileExt);
            fileInfo.setFileSize(file.getSize());
            fileInfo.setFileType(file.getContentType());
            fileInfo.setCreateTime(System.currentTimeMillis()/1000);
            fileInfo.setAlias(file.getOriginalFilename());
            fileInfo.setStorage("local");

            return fileInfo;

        } catch (IOException e) {
            log.error("文件上传失败", e);
            throw new CommonException("文件上传失败：" + e.getMessage());
        } catch (Exception e) {
            log.error("文件上传异常", e);
            throw new CommonException("文件上传异常：" + e.getMessage());
        }
    }

    /**
     * 删除文件
     * @param filePath 文件路径
     * @return 是否删除成功
     */
    public boolean deleteFile(String filePath) {
        try {
            Path path = Paths.get(uploadPath, filePath);
            if (Files.exists(path)) {
                return Files.deleteIfExists(path);
            }
            return true;
        } catch (Exception e) {
            log.error("删除文件失败，文件路径: {}", filePath, e);
            return false;
        }
    }

    /**
     * 检查是否为图片文件
     */
    private boolean isImageFile(String filename) {
        if (filename == null) {
            return false;
        }
        String lowerCase = filename.toLowerCase();
        return lowerCase.endsWith(".jpg") || lowerCase.endsWith(".jpeg") || 
               lowerCase.endsWith(".png") || lowerCase.endsWith(".gif") || 
               lowerCase.endsWith(".bmp") || lowerCase.endsWith(".webp");
    }

    /**
     * 获取文件扩展名
     */
    private String getFileExtension(String filename) {
        int lastDotIndex = filename.lastIndexOf('.');
        return lastDotIndex > 0 ? filename.substring(lastDotIndex + 1) : "";
    }

    /**
     * 生成唯一文件名
     */
    private String generateFileName(String fileExt) {
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        String uuid = UUID.randomUUID().toString().replace("-", "").substring(0, 8);
        return timestamp + uuid + "." + fileExt;
    }

} 